package com.runen.infinitemovement.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.runen.infinitemovement.App;
import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.ChallengeAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.GpsDataEntity;
import com.runen.infinitemovement.model.entity.RetrunSaveSportsEntity;
import com.runen.infinitemovement.model.entity.SaveSportsRecordEntity;
import com.runen.infinitemovement.model.entity.SaveStopStartsEntity;
import com.runen.infinitemovement.model.entity.SportsStopEntity;
import com.runen.infinitemovement.model.entity.StartChallengeEntity;
import com.runen.infinitemovement.model.enums.SPCompat;
import com.runen.infinitemovement.service.LocationService;
import com.runen.infinitemovement.steputil.StepUtil;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.DensityUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.tool.notchtool.NotchTools;
import com.runen.infinitemovement.tool.notchtool.core.NotchProperty;
import com.runen.infinitemovement.tool.notchtool.core.OnNotchCallBack;
import com.runen.infinitemovement.track.recorduitl.BackStageManagementUtil;
import com.runen.infinitemovement.track.recorduitl.BitmapUtil;
import com.runen.infinitemovement.track.recorduitl.PathSmoothTool;
import com.runen.infinitemovement.widget.popupwind.CommonDialog;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.JsonUtils;
import com.runen.rxnetlibrary.utils.LogUtil;
import com.runen.rxnetlibrary.utils.SharePreferenceUtils;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SportsStatusActivity extends BaseActivity implements LocationSource,
        AMap.OnMapTouchListener, AMap.OnMapScreenShotListener, Handler.Callback {
    private final String TAG = "SportsStatusActivity";
    @BindView(R.id.tv_distance)
    TextView tvDistance;
    @BindView(R.id.tv_use_time)
    TextView tvUseTime;
    @BindView(R.id.tv_speed)
    TextView tvSpeed;
    @BindView(R.id.tv_speed_title)
    TextView tvSpeedTitle;
    @BindView(R.id.mapView)
    TextureMapView mapView;
    @BindView(R.id.iv_pause)
    ImageView ivPause;
    @BindView(R.id.tv_pause)
    TextView tvPause;
    @BindView(R.id.ll_pause)
    LinearLayout llPause;
    @BindView(R.id.iv_proceed)
    ImageView ivProceed;
    @BindView(R.id.tv_proceed)
    TextView tvProceed;
    @BindView(R.id.ll_proceed)
    LinearLayout llProceed;
    @BindView(R.id.rl_map)
    RelativeLayout rlMap;
    private int sportsType;
    private AMap mAMap;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private PolylineOptions mPolyoptions;
    private Polyline mpolyline;
    private PolylineOptions pusePolyoptions;
    private Polyline pusePolyline;
    private AMapLocation lastAMapLocation;
    private boolean canMove = true;//变量控制拖动不返回中心点
    private String sportRecordId;
    private SaveSportsRecordEntity saveSportsRecordEntity;
    private GpsDataEntity gpsDataBean;
    private List<GpsDataEntity> gpsDataBeanList = new ArrayList<>();
    private SaveStopStartsEntity saveStopStartsEntity;
    private List<Double> altitudesBeanList = new ArrayList<>();
    public static final String RECEIVER_ACTION = "location_in_background";
    /**
     * 当前运动距离
     */
    private double mDistance = 0;
    /**
     * 当前运动距离
     */
    private double puseDistance = 0;
    /**
     * 是否开始
     */
    private boolean isStart;

    /**
     * 是否暂停
     */
    private boolean isPause;
    private boolean isPauseDistance;
    private int weather;
    /**
     * 声音池
     */
    private SoundPool soundPool;
    // JobService，执行系统任务
    private int setCount;
    private boolean isBind = false;
    private Messenger mGetReplyMessenger = new Messenger(new Handler(this));
    private Messenger messenger;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sports_status;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        initStartAnimation();
    }

    /**
     * 暂时运动页面
     */
    private void initSportsView() {
        init();
        initPolyline();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(RECEIVER_ACTION);
//        registerReceiver(locationChangeBroadcastReceiver, intentFilter);
//        setCount = SharePreferenceUtils.getInt(this, "setCount");
//        if (setCount < 1) {
//            openPeminsss();
//            SharePreferenceUtils.putInt(this, "setCount", setCount + 1);
//        }
        saveStopStartsEntity = new SaveStopStartsEntity();
        saveStopStartsEntity.strideFrequencies = new ArrayList<>();
        saveSportsRecordEntity = new SaveSportsRecordEntity();
        sportsType = getIntent().getIntExtra("SPORTS_TYPE", 0);
        sportRecordId = getIntent().getStringExtra("sportRecordId");
        weather = getIntent().getIntExtra("weather", 1);
        saveStopStartsEntity.sportRecordId = sportRecordId;

        saveSportsRecordEntity.taskId = sportRecordId;
        saveSportsRecordEntity.userId = UserAPI.getUserId();

        int steps = StepUtil.getTodayStep(SportsStatusActivity.this);
        SharePreferenceUtils.putInt(this, SPCompat.SPORT_START_STEPS, steps);

        if (sportsType == 1) {
            tvSpeed.setText("0.00");
            tvSpeedTitle.setText("平均速度（km/h）");
        } else {
            mHandler.sendEmptyMessage(1);
            tvSpeed.setText("0'00''");
            tvSpeedTitle.setText("平均配速");
        }
    }

    private void stopPlayMusicService() {
        Intent intent = new Intent(SportsStatusActivity.this, LocationService.class);
        stopService(intent);
    }

    @SuppressLint("NewApi")
    private void startPlayMusicService() {
        Intent intent = new Intent(SportsStatusActivity.this, LocationService.class);
        isBind = bindService(intent, connection, Context.BIND_AUTO_CREATE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            getApplicationContext().startForegroundService(intent);
        } else {
            getApplicationContext().startService(intent);
        }
    }


    private IBinder myService;
    private TimerTask serverTimerTask;
    private Timer serverTimer;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, final IBinder service) {
            /**
             * 设置定时器，每个两秒钟去更新一次运动数据
             */
            myService = service;
            messenger = new Messenger(myService);
            serverTimerTask = new TimerTask() {
                @Override
                public void run() {
                    handler.sendEmptyMessage(1);
                }
            };
            serverTimer = new Timer();
            serverTimer.scheduleAtFixedRate(serverTimerTask, 0, 2000);
        }

        /**
         * 当与Service之间的连接丢失的时候会调用该方法，
         * 这种情况经常发生在Service所在的进程崩溃或者被Kill的时候调用，
         * 此方法不会移除与Service的连接，当服务重新启动的时候仍然会调用 onServiceConnected()。
         * @param name 丢失连接的组件名称
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                try {
                    Message msgs = Message.obtain(null, Constant.MSG_SPORTS_FROM_CLIENT);
                    Bundle bundle = new Bundle();
                    bundle.putLong("myTime", userTime * 1000);
                    bundle.putBoolean("myIsPause", isPause);
                    bundle.putDouble("distance", mDistance);
                    bundle.putInt("SPORTS_TYPE", sportsType);
                    bundle.getString("sportRecordId", sportRecordId);
                    msgs.setData(bundle);
                    msgs.replyTo = mGetReplyMessenger;
                    messenger.send(msgs);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }
    });


    private String content;

    private void openPeminsss() {
        if (BackStageManagementUtil.getMobileType().equals("xiaomi")) {
            content = "请选择后台配置为【无限制】，以便我们能为您更准确地记录运动数据。";
        } else if (BackStageManagementUtil.getMobileType().equals("huawei") || BackStageManagementUtil.getMobileType().equals("honor")) {
            content = "请在自动管理中找到【无涯运动】，并关闭自动管理选项，在弹出的弹窗中打开【允许自动启动】和【允许后台活动】权限，以便我们能为您更准确地记录运动数据。";
        } else if (BackStageManagementUtil.getMobileType().equals("vivo")) {
            content = "请在自动管理中找到【无涯运动】，并关闭自动管理选项，在弹出的弹窗中打开【允许自动启动】和【允许后台活动】权限，以便我们能为您更准确地记录运动数据。";
        } else {
            content = "请在自动管理中找到【无涯运动】，并关闭自动管理选项，在弹出的弹窗中打开【允许自动启动】和【允许后台活动】权限，以便我们能为您更准确地记录运动数据。";
        }

        CommonDialog.getInstance(this, "", content, "取消", "去设置", 0).setOnClickListener(new CommonDialog.OnClickListener() {
            @Override
            public void onSendListener() {

            }

            @Override
            public void onDismiss() {
                BackStageManagementUtil.jumpStartInterface(SportsStatusActivity.this);
            }
        });

    }

    private void initPolyline() {
        mPolyoptions = new PolylineOptions();
        mPolyoptions.width(20f);
        mPolyoptions.geodesic(true);//大地曲线
        mPolyoptions.color(CommonUtil.getColor(R.color.color_FFF8494A));

        pusePolyoptions = new PolylineOptions();
        pusePolyoptions.width(20f);
        pusePolyoptions.geodesic(true);//大地曲线
        pusePolyoptions.color(Color.GRAY);
    }

    /***
     *  时间记录
     */
    private Timer timer;
    private TimerTask timerTask;
    private long restoreTime;
    private long mStartTime;
    private int lastPausetime;
    int time;
    public static long myTime;

    /**
     * 开始运动计时
     */
    private void startTimer() {
        mStartTime = SystemClock.elapsedRealtime() - restoreTime;
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                time = lastPausetime + (int) ((SystemClock.elapsedRealtime() - mStartTime) / 1000);
                String hh = new DecimalFormat("00").format(time / 3600);
                String mm = new DecimalFormat("00").format(time % 3600 / 60);
                String ss = new DecimalFormat("00").format(time % 60);
                String timeFormat = new String(hh + ":" + mm + ":" + ss);
                Message msg = new Message();
                Bundle bundle = new Bundle();
                bundle.putInt("userTime", time);
                bundle.putString("timeFormat", timeFormat);
                msg.setData(bundle);
                msg.what = 1;
                startTimeHandler.sendMessage(msg);
            }
        };

        if (timer != null && timerTask != null) {
            timer.scheduleAtFixedRate(timerTask, 0, 1000L);
        }
    }

    private int userTime;
    private Handler startTimeHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                if (null != tvUseTime) {
                    Bundle bundle = msg.getData();
                    userTime = bundle.getInt("userTime");
                    String timeFormat = bundle.getString("timeFormat");
                    tvUseTime.setText(timeFormat);
                    if (userTime != 0) {
                        if (userTime % 20 == 0) {
                            if (TextUtils.isEmpty(sportRecordId)) {
                                getSportsId(0);
                            } else {
                                saveRecord();
                            }
                        }
                        //步频
                        if (userTime % 60 == 0) {
                            lastStep = steps - lastStep;
                            saveStopStartsEntity.strideFrequencies.add(lastStep);
                            lastStep = steps;
                        }
                    }
                }
            }
            return false;
        }
    });

    private void getSportsId(int label) {
        JSONObject object = new JSONObject();
        try {
            object.put("type", sportsType);
            object.put("weather", weather);
            object.put("phoneModel", BackStageManagementUtil.getMobileType());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ChallengeAPI().onStartChallenge(object.toString(), new BaseResultCallback<StartChallengeEntity>() {
            @Override
            public void onResponse(StartChallengeEntity response) {
                if (response.code == 0) {
                    if (response.data != null) {
                        sportRecordId = response.data.sportRecordId;
                        saveStopStartsEntity.sportRecordId = sportRecordId;
                        saveSportsRecordEntity.taskId = sportRecordId;
                        if (label == 0) {
                            saveRecord();
                        } else {
                            if (smallMap()) {
                                showDialog("保存记录中...", false);
                                mAMap.getMapScreenShot(SportsStatusActivity.this);
                            }
                        }
                    }
                }
            }
        });
    }

    //是否有当天的记录
    private boolean hasRecord;
    //未记录之前的步数
    private int hasStepCount;
    private int steps;
    private int tempSteps;

    /***
     *  暂停时间记录
     */
    private Timer puseTimer;
    private TimerTask puseTimerTask;
    private long puseRestoreTime;
    private long puseStartTime;
    private int puseLastPausetime;
    int puseTime;

    /**
     * 开始运动计时
     */
    private void puseStartTimer() {
        puseStartTime = SystemClock.elapsedRealtime() - puseRestoreTime;
        puseTimer = new Timer();
        puseTimerTask = new TimerTask() {
            @Override
            public void run() {
                puseTime = puseLastPausetime + (int) ((SystemClock.elapsedRealtime() - puseStartTime) / 1000);
                Message msg = new Message();
                Bundle bundle = new Bundle();
                bundle.putInt("puseTime", puseTime);
                msg.setData(bundle);
                msg.what = 1;
                puseStartTimeHandler.sendMessage(msg);
            }
        };

        if (puseTimer != null && puseTimerTask != null) {
            puseTimer.scheduleAtFixedRate(puseTimerTask, 0, 1000L);
        }
    }

    private int puseUserTime;
    private Handler puseStartTimeHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                if (null != tvUseTime) {
                    Bundle bundle = msg.getData();
                    puseUserTime = bundle.getInt("puseTime");
                    if (puseUserTime != 0) {
                        if (puseUserTime % 20 == 0) {
                            saveRecord();
                        }
                    }
                }
            }
            return false;
        }
    });

    private void init() {
        if (mAMap == null) {
            mAMap = mapView.getMap();
        }
//        MapUtils.setCustomMap(this, mAMap);
        setUpMap();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            SoundPool.Builder builder = new SoundPool.Builder();
            builder.setMaxStreams(1);
            AudioAttributes.Builder aab = new AudioAttributes.Builder();
            aab.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC);
            aab.setLegacyStreamType(AudioManager.STREAM_DTMF);
            aab.setUsage(AudioAttributes.USAGE_MEDIA);
            builder.setAudioAttributes(aab.build());
            soundPool = builder.build();
        } else {
            soundPool = new SoundPool(1, AudioManager.STREAM_DTMF, 0);
        }
        startSport();
    }

    private void startSport() {
        if (!isStart) {
            isStart = true;
            isPause = false;
            setViewStartStatus();
        }

    }

    private void setViewStartStatus() {
        playAudio(R.raw.sports_start);
        startTimer();
        // 4. 启动播放音乐Service
        startPlayMusicService();
    }

    /**
     * 播放声音
     *
     * @param resId
     */
    private void playAudio(int resId) {
        if (soundPool != null) {
            soundPool.load(this, resId, 0);
            soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                @Override
                public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                    soundPool.play(sampleId, 1, 1, 0, 0, 1);
                }
            });
        }
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        /**
         * 设置一些amap的属性
         */

        LatLng latLng = new LatLng(30.65985, 104.06325);//构造一个位置
        mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));
        UiSettings uiSettings = mAMap.getUiSettings();
        uiSettings.setCompassEnabled(false);// 设置指南针是否显示
        uiSettings.setZoomControlsEnabled(false);// 设置缩放按钮是否显示
        uiSettings.setScaleControlsEnabled(true);// 设置比例尺是否显示
        uiSettings.setRotateGesturesEnabled(true);// 设置地图旋转是否可用
        uiSettings.setTiltGesturesEnabled(true);// 设置地图倾斜是否可用
        uiSettings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示

        /** 自定义系统定位小蓝点
         *
         */
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        Bitmap bg = BitmapUtil.decodeSamledBitmaoFromResource(getResources(),
                R.mipmap.ico_myself, 48, 48);
        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bg);
        myLocationStyle.myLocationIcon(bitmapDescriptor);
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));//设置定位蓝点精度圆圈的边框颜色的方法。
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));//设置定位蓝点精度圆圈的填充颜色的方法。
        myLocationStyle.strokeWidth(0);//设置定位蓝点精度圈的边框宽度的方法。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        myLocationStyle.interval(2000);
        mAMap.setMyLocationStyle(myLocationStyle);
        mAMap.setLocationSource(this);// 设置定位监听
        mAMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        mAMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        mAMap.setOnMapTouchListener(this);
        // 设置定位的类型为定位模式，有定位、跟随或地图根据面向方向旋转几种
//        mAMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
    }

    /**
     * 标记我的起始位置
     */
    private Marker mlocMarker;
    private double latitude = 0;
    private double longitude = 0;

    private void startPoint() {
        if (mlocMarker != null) {
            mlocMarker.remove();
        }
        mlocMarker = mAMap.addMarker(
                new MarkerOptions()
                        .title("起点")
                        .snippet("我的起始位置")
                        .position(new LatLng(latitude, longitude))
                        .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),
                                R.mipmap.ico_my_start_point))).anchor(0.5f, 0.5f));
    }

    private List<LatLng> latLngList = new ArrayList<>();


    private AMapLocation prev;
    private double intervalMin = 2;
    private double intervalMax = 25;
    private boolean staticFlag;
    private int count;
    private boolean isSend;

    /**
     * 判断飘点
     *
     * @param location
     * @return
     */
    public boolean intercept(AMapLocation location) {

        if (prev != null) {
            LatLng s = new LatLng(prev.getLatitude(), prev.getLatitude());
            LatLng d = new LatLng(location.getLatitude(), location.getLatitude());
            float distance = AMapUtils.calculateLineDistance(s, d);//距离改变量,单位米
//            LLog.print("距离改变量: "+ distance+" 米");
            if (distance < intervalMin) {
//                LLog.print("距离改变量过小: "+ distance+" 米");
                if (distance < 1) {
                    if (!staticFlag) {
                        count++; //收集连续多次的距离改变量
                        if (count == 10) {
                            staticFlag = true;
                            count = 0;
                            LogUtil.e("staticFlag", "进入静止状态");
                        }
                    } else {
//                        LLog.print("当前处于静止");
                        if (count > 0) count--;
                    }
                }
                //如果连续10次距离改变量==0 认为处于静止状态, 解除静止状态的条件: 连续3次大的距离改变
                return true;
            }

            if (staticFlag) {
                count++;
                if (count == 3) {
                    staticFlag = false;
                    count = 0;
                    LogUtil.e("staticFlag", "进入移动状态");
                }
            } else {
//                LLog.print("当前移动正常");
                if (count > 0) count--;
            }

            if (distance < intervalMax) {
                float time = (location.getTime() - prev.getTime()) / 1000.0f; //两点的时间差
                if (time <= 0) {
                    //LLog.print("时间异常: " + time);
                    return true;
                } else {
//                    prev.setTime(location.getTime());
                    float speed = distance / time; // m/s ,车辆速度最大值  50米/秒(m/s)=180千米/时(km/h)
                    if (speed < 1.5) {
                        LogUtil.e("staticFlag", "速度过小: " + speed + " 米/秒");
                    } else if (speed > 30) {
                        LogUtil.e("staticFlag", "速度过大: " + speed + " 米/秒");
                    }
                }
            }
        }

        if (staticFlag) {
            LogUtil.e("staticFlag", "静止状态");
            return true;
        }
        LogUtil.e("staticFlag", "移动状态");
        prev = location;

        return false;
    }

    public boolean intercept(GpsDataEntity location) {
        if (location.horizontalAccuracy > 100)
            return true;
        if (location.speed == 0)
            return true;
        return false;
    }


    /**
     * 暂停时记录时间距离
     */
    private void puseBindView(AMapLocation curLocation, GpsDataEntity entity) {
        if (lastAMapLocation == null) {
            return;
        }
        //距离的计算
        if (!isPauseDistance) {
            lastAMapLocation = curLocation;
            isPauseDistance = false;
            puseDistance = puseDistance + AMapUtils.calculateLineDistance(new LatLng(lastAMapLocation.getLatitude(), lastAMapLocation.getLongitude()),
                    new LatLng(curLocation.getLatitude(), curLocation.getLongitude()));
        } else {
            puseDistance = puseDistance + AMapUtils.calculateLineDistance(new LatLng(lastAMapLocation.getLatitude(), lastAMapLocation.getLongitude()),
                    new LatLng(curLocation.getLatitude(), curLocation.getLongitude()));
        }

        //20秒传送数据
//        gpsDataBean.altitude = entity.altitude;
//        gpsDataBean.horizontalAccuracy = curLocation.getAccuracy();
//        gpsDataBean.latitude = curLocation.getLatitude();
//        gpsDataBean.longitude = curLocation.getLongitude();
//        gpsDataBean.speed = 0;
//        gpsDataBean.timestamp = System.currentTimeMillis();
//        gpsDataBean.type = curLocation.getLocationType();
//        gpsDataBean.course = curLocation.getBearing();
//        gpsDataBeanList.add(gpsDataBean);

        gpsDataBean.altitude = entity.altitude;
        gpsDataBean.horizontalAccuracy = entity.horizontalAccuracy;
        gpsDataBean.latitude = entity.latitude;
        gpsDataBean.longitude = entity.longitude;
        gpsDataBean.speed = 0;
        gpsDataBean.timestamp = System.currentTimeMillis();
        gpsDataBean.type = entity.type;
        gpsDataBean.course = entity.course;
        gpsDataBeanList.add(gpsDataBean);
    }


    int lastStep = 0;

    private void bindView(AMapLocation curLocation, GpsDataEntity entity) {
        if (lastAMapLocation == null) {
            return;
        }
        //距离的计算
        if (isPauseDistance) {
            lastAMapLocation = curLocation;
            isPauseDistance = false;
            mDistance = mDistance + AMapUtils.calculateLineDistance(new LatLng(lastAMapLocation.getLatitude(), lastAMapLocation.getLongitude()),
                    new LatLng(curLocation.getLatitude(), curLocation.getLongitude()));
        } else {
            mDistance = mDistance + AMapUtils.calculateLineDistance(new LatLng(lastAMapLocation.getLatitude(), lastAMapLocation.getLongitude()),
                    new LatLng(curLocation.getLatitude(), curLocation.getLongitude()));
        }

        tvDistance.setText(String.valueOf(CommonUtil.Double2position(mDistance / 1000)));
        double v = entity.speed * 3.6;
        int speed_allocationInt = 0;
        int speed_allocationMode = 0;
        double mm = (double) userTime / 60;
        double averageSpeed = 0;
        if (mDistance > 0 && userTime > 0) {
            double km = mDistance / 1000;
            speed_allocationInt = (int) (mm / km);
            double ss = mm % km;
            speed_allocationMode = (int) ss;
            if (km > 0) {
                averageSpeed = km * 3600 / userTime;
            }

            switch (sportsType) {
                case 1:
                    tvSpeed.setText(String.valueOf(CommonUtil.Double2position(averageSpeed)));
                    break;
                default:
                    tvSpeed.setText(speed_allocationInt + "'" + speed_allocationMode + "''");
                    break;
            }
//            LogUtil.e("配速", speed_allocationInt + "'" + speed_allocationMode + "''-----" + km + "---" + mm + "---" + userTime+"---"+ss);
        }

        //20秒传送数据
        gpsDataBean.altitude = entity.altitude;
        gpsDataBean.horizontalAccuracy = entity.horizontalAccuracy;
        gpsDataBean.latitude = entity.latitude;
        gpsDataBean.longitude = entity.longitude;
        gpsDataBean.speed = v;
        gpsDataBean.timestamp = System.currentTimeMillis();
        gpsDataBean.type = entity.type;
        gpsDataBean.course = entity.course;
        gpsDataBeanList.add(gpsDataBean);
        //结束传送数据
        double climb = 0;
        altitudesBeanList.add(entity.altitude);
        double ch = 0;
        double fh = 0;
        if (altitudesBeanList.size() > 0) {
            double postion = altitudesBeanList.get(0);
            for (int i = 0; i < altitudesBeanList.size(); i++) {
                double temp;
                temp = postion - altitudesBeanList.get(i);
                climb = temp;
                if (temp > 0) {
                    ch += temp;
                } else {
                    fh += temp;
                }
                postion = altitudesBeanList.get(i);
            }
        }
        int step = (int) (mDistance / 0.6);
        saveStopStartsEntity.steps = step;
    }


    @Override
    public void activate(OnLocationChangedListener listener) {
        canMove = true;
        mListener = listener;
    }


    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }


    private List<LatLng> rectifications = new ArrayList<>();

    /**
     * 实时轨迹画线
     */
    private void redrawline(List<LatLng> rectifications) {
        if (rectifications.size() <= 2) return;
        if (mpolyline != null) {
            mpolyline.remove();
        }

        //高德官方提供的抽稀去燥工具
        PathSmoothTool pathSmoothTool = new PathSmoothTool();
        pathSmoothTool.setIntensity(4);
        rectifications = pathSmoothTool.pathOptimize(rectifications);

        // 绘制一个大地曲线
        mpolyline = mAMap.addPolyline((new PolylineOptions())
                .addAll(rectifications).geodesic(true)
                .width(20f).color(CommonUtil.getColor(R.color.color_FFF8494A)));
//        if (mPolyoptions.getPoints().size() > 1) {
//            if (mpolyline != null) {
//                mpolyline.setPoints(mpolyline.getPoints());
//            } else {
//                mpolyline = mAMap.addPolyline(mPolyoptions);
//            }
//        }
    }

    /**
     * 实时轨迹画线
     */
    private void puseRedrawline() {
        if (pusePolyoptions.getPoints().size() > 1) {
            if (pusePolyline != null) {
                pusePolyline.setPoints(pusePolyoptions.getPoints());
            } else {
                pusePolyline = mAMap.addPolyline(pusePolyoptions);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        mHandler.removeMessages(1);
        if (isBind) this.unbindService(connection);
    }


    @OnClick({R.id.ll_pause, R.id.ll_proceed})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_pause:

                if (isPause) {
                    isPause = false;
                    isPauseDistance = true;
                    changViewProceed();
                } else {
                    isPause = true;
                    changViewPause();
                }
                handler.sendEmptyMessage(1);
                break;
            case R.id.ll_proceed:
                if (isStop) {
                    changViewStop();
                    //关闭启动播放音乐Service
                    stopPlayMusicService();
                } else {
                    isPause = true;
                    changViewPause();
                    handler.sendEmptyMessage(1);
                }
                break;
        }
    }

    private boolean isStop;

    /**
     * 暂停改变view
     */
    private void changViewPause() {
        llPause.setVisibility(View.VISIBLE);
        GlideUtils.loadImage(this, CommonUtil.getDrawable(R.mipmap.ico_stop), ivProceed);
        tvProceed.setText("结束");
        playAudio(R.raw.sports_puase);
        startTimeHandler.removeMessages(1);
        timer.cancel();
        timerTask.cancel();
        lastPausetime = time;
        isStop = true;
        //暂停运动是计算暂停时间
        puseStartTimer();
    }

    /**
     * 继续运动改变view
     */
    private void changViewProceed() {
        llPause.setVisibility(View.GONE);
        GlideUtils.loadImage(this, CommonUtil.getDrawable(R.mipmap.ico_proceed), ivProceed);
        tvProceed.setText("暂停");
        playAudio(R.raw.sports_resume);
        startTimer();
        isStop = false;
        //继续运动是暂停
        puseTimer.cancel();
        puseTimerTask.cancel();
        puseLastPausetime = puseTime;
        puseStartTimeHandler.removeMessages(1);
    }

    /**
     * 点击结束运动
     */
    private void changViewStop() {
        startTimeHandler.removeMessages(1);
        if (timer != null) {
            timer.cancel();
        }
        if (timerTask != null) {
            timerTask.cancel();
        }
        playAudio(R.raw.sports_stop);
        puseStartTimeHandler.removeMessages(1);
        if (puseTimer != null) {
            puseTimer.cancel();
        }
        if (puseTimerTask != null) {
            puseTimerTask.cancel();
        }
        saveStop();
    }

    @Override
    public void onTouch(MotionEvent motionEvent) {
        if (canMove) {
            //用户拖动地图后，不再跟随移动，直到用户点击定位按钮
            canMove = false;
            new Thread(
                    new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            canMove = true;
                        }
                    }
            ).start();
        }
    }


    private void saveRecord() {
        saveSportsRecordEntity.gpsData = new ArrayList<>();
        saveSportsRecordEntity.gpsData.addAll(gpsDataBeanList);
        if (saveSportsRecordEntity.gpsData.size() > 0) {
            new ChallengeAPI().saveSportsRecord(JsonUtils.toJson(saveSportsRecordEntity), new BaseResultCallback<RetrunSaveSportsEntity>() {
                @Override
                public void onResponse(RetrunSaveSportsEntity response) {
                    gpsDataBeanList.clear();
                    saveSportsRecordEntity.gpsData.clear();
                }

                @Override
                public void onComplete() {
                    super.onComplete();
                }
            });
        }
    }

    @Override
    public void onBackPressed() {
        if (rl_start_animation.getVisibility() == View.GONE)
            CommonDialog.getInstance(this, "是否要结束本次挑战？", "确定")
                    .setOnClickListener(new CommonDialog.OnClickListener() {
                        @Override
                        public void onSendListener() {
                            changViewStop();
                            //关闭启动播放音乐Service
                            stopPlayMusicService();
                            saveStop();
                        }

                        @Override
                        public void onDismiss() {

                        }
                    });
    }

    private LatLngBounds.Builder newBounds = new LatLngBounds.Builder();

    private void saveStop() {

        if (TextUtils.isEmpty(sportRecordId)) {
            getSportsId(1);
        } else {
            showDialog("保存记录中...", false);
            if (smallMap()) {
                mAMap.getMapScreenShot(this);
            }
        }
    }

    private boolean smallMap() {
        for (int j = 0; j < latLngList.size(); j++) {
            newBounds.include(new LatLng(latLngList.get(j).latitude, latLngList.get(j).longitude));
        }
        if (mAMap != null) {
            mAMap.animateCamera(CameraUpdateFactory.newLatLngBounds(newBounds.build(), 15), null);
            return true;
        }
        return false;
    }

    private void sendStop(String url) {
        if (null != saveStopStartsEntity) {
            if (!TextUtils.isEmpty(url)) {
                saveStopStartsEntity.sportImage = url;
            }
            if (gpsDataBeanList.size() > 0) {
                saveStopStartsEntity.gpsData = new ArrayList<>();
                saveStopStartsEntity.gpsData.addAll(gpsDataBeanList);
            } else {
                saveStopStartsEntity.gpsData = null;
            }
//
//            if (saveStopStartsEntity.strideFrequencies != null || saveStopStartsEntity.strideFrequencies.size() == 0) {
//                saveStopStartsEntity.strideFrequencies = null;
//            }
            saveStopStartsEntity.steps = steps;
            int stopSteps = SharePreferenceUtils.getInt(this, SPCompat.SPORT_START_STEPS, 0);
            int currentSteps = StepUtil.getTodayStep(this);
            if (currentSteps - stopSteps > 0) {
                saveStopStartsEntity.steps = currentSteps - stopSteps;
            }
        }
        new ChallengeAPI().saveStopSportsRecord(JsonUtils.toJson(saveStopStartsEntity), new BaseResultCallback<SportsStopEntity>() {
            @Override
            public void onResponse(SportsStopEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    Intent intent = new Intent(SportsStatusActivity.this, StopSportsActivity.class);
                    intent.putExtra("imgUrl", url);
                    intent.putExtra("motionId", sportRecordId);
                    intent.putExtra("medal", JsonUtils.toJson(response));
                    startActivity(intent);
                    EventBus.getDefault().post(new EventBusEntity(99));
                    finish();
                } else {
                    if (response.msg.contains("没有GPS数据")) {
                        finish();
                    }
                    ToastUtils.showShort(response.msg);
                }
            }
        });
    }

    @Override
    public void onMapScreenShot(Bitmap bitmap) {
        EventBus.getDefault().post(new EventBusEntity(101));
//        Bitmap screenShotBitmap = ScreenShotHelper.getMapAndViewScreenShot(bitmap, rlMap, mapView);
        sendStop("");
//        File file = ScreenShotHelper.compressImage(screenShotBitmap, this);
//        TreeMap<String, String> mapType = new TreeMap<>();
//        mapType.put("type", "mapImg");
//        TreeMap<String, File> mapFile = new TreeMap<>();
//        mapFile.put("file", file);
//
//        new UserAPI().putFile(mapType, mapFile, new BaseResultCallback<PictrueEntity>() {
//            @Override
//            public void onResponse(PictrueEntity response) {
//                if (response.code == 0) {
//                    if (response.data != null) {
//                        LogUtil.e("file", response.data.url);
//
//                        sendStop(response.data.url);
//                    }
//                } else {
//                    ToastUtils.showShort(response.msg);
//                }
//            }
//        });
    }


    @Override
    public void onMapScreenShot(Bitmap bitmap, int i) {
//
    }


    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                int zSteps = 0;
                zSteps = StepUtil.getTodayStep(App.getInstance());
                if (!hasRecord) {
                    hasRecord = true;
                    hasStepCount = zSteps;
                } else {
                    int thisStepCount = zSteps - hasStepCount;
                    steps += (thisStepCount - tempSteps);
                    tempSteps = thisStepCount;
                }
                mHandler.sendEmptyMessageDelayed(1, 3000);
            }
            return false;
        }
    });

//    private int count111 = 0;

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        switch (msg.what) {
            //这里用来获取到Service发来的数据
            case Constant.MSG_SPORTS_FROM_SERVER:
                AMapLocation aMapLocation = JsonUtils.fromJson(msg.getData().getString("AMapLocation"), AMapLocation.class);
                GpsDataEntity gpsDataEntity = JsonUtils.fromJson(msg.getData().getString("GpsDataEntity"), GpsDataEntity.class);
                if (mListener != null && aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
//                        isSend = intercept(aMapLocation);
                        isSend = intercept(gpsDataEntity);

                        if (!isSend) {
                            if (aMapLocation.getAccuracy() <= 50) {
                                if (latitude == 0 && longitude == 0) {
                                    latitude = aMapLocation.getLatitude();
                                    longitude = aMapLocation.getLongitude();
                                    startPoint();
                                }
                                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                                LatLng myLocation = new LatLng(aMapLocation.getLatitude(),
                                        aMapLocation.getLongitude());

                                latLngList.add(myLocation);
                                if (canMove) {
                                    mAMap.animateCamera(CameraUpdateFactory.newLatLng(myLocation));
                                }
                                gpsDataBean = new GpsDataEntity();

                                if (!isPause) {
                                    gpsDataBean.state = 0;
                                    mPolyoptions.add(myLocation);
                                    rectifications.add(myLocation);
                                    redrawline(rectifications);
                                    bindView(aMapLocation, gpsDataEntity);
                                    lastAMapLocation = aMapLocation;
                                } else {
                                    pusePolyoptions.add(myLocation);
                                    puseRedrawline();
                                    puseBindView(aMapLocation, gpsDataEntity);
                                    lastAMapLocation = aMapLocation;
                                    gpsDataBean.state = 1;
                                }
                            }
                        }
                    } else {
                        String errText = "定位失败," + aMapLocation.getErrorCode() + ": "
                                + aMapLocation.getErrorInfo();
                        Log.e("AmapErr", errText);
                    }
                }
                break;
        }
        return false;
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    /**
     * ============================进入该页面，展示该动画===============================================
     */
    static final int ANIMATION_DURATION = 300;
    static final int SOUNDPOOL_MAX_STREAMS = 3;
    static final int SOUNDPOOL_LEFT_VOLUME = 1;
    static final int SOUNDPOOL_RIGHT_VOLUME = 1;
    static final int SOUNDPOOL_PRIORITY = 0;
    static final int SOUNDPOOL_LOOP = 0;
    static final int SOUNDPOOL_RATE = 1;
    static final int MSG_IN_ANIMATION = 0x1502;
    static final int MSG_OUT_ANIMATION = 0x1503;
    static final int MSG_PAY_AUDIOS = 0x1504;

    private SoundPool startSoundPool;
    AnimationHandler animationHandler;
    AnimatorListenerAdapter inAdapter;
    AnimatorListenerAdapter outAdapter;
    Map<Integer, Map<String, Integer>> audios;
    int index;
    @BindView(R.id.iv_num)
    ImageView ivNum;
    @BindView(R.id.rl_start_animation)
    RelativeLayout rl_start_animation;
    @BindView(R.id.ll_content)
    LinearLayout ll_content;
    private int weatherType;

    private void initStartAnimation() {
        //适配刘海屏
        NotchTools.getFullScreenTools().translucentStatusBar(this, new OnNotchCallBack() {
            @Override
            public void onNotchPropertyCallback(NotchProperty notchProperty) {
                ll_content.setPadding(0, CommonUtil.getStatusBarHeight(SportsStatusActivity.this), 0, 0);
            }
        });
        animationHandler = new AnimationHandler(this);
        initArgs();
        initAudio();
        initListener();
        execute();
    }

    private void initArgs() {
        sportsType = getIntent().getIntExtra("SPORTS_TYPE", 0);
        weatherType = getIntent().getIntExtra("weatherType", 1);
    }

    private void initAudio() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            SoundPool.Builder builder = new SoundPool.Builder();
            builder.setMaxStreams(SOUNDPOOL_MAX_STREAMS);
            AudioAttributes.Builder aab = new AudioAttributes.Builder();
            aab.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC);
            aab.setLegacyStreamType(AudioManager.STREAM_DTMF);
            aab.setUsage(AudioAttributes.USAGE_MEDIA);
            builder.setAudioAttributes(aab.build());
            startSoundPool = builder.build();
        } else {
            startSoundPool = new SoundPool(SOUNDPOOL_MAX_STREAMS, AudioManager.STREAM_DTMF, 0);
        }
        audios = new LinkedHashMap<>();
        int[] raws = new int[]{R.raw.n3, R.raw.n2, R.raw.n1};
        for (int index = 0; index < raws.length; index++) {
            Map<String, Integer> audio = new LinkedHashMap<>();
            audio.put("id", startSoundPool.load(this, raws[index], 0));
            audio.put("duration", getAudioDuration(raws[index]));
            audios.put(index, audio);
        }
    }

    private void initListener() {
        inAdapter = new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                if (3 - index == 1) {
                    ivNum.setImageResource(R.mipmap.ico_1);
                } else if (3 - index == 2) {
                    ivNum.setImageResource(R.mipmap.ico_2);
                    animationHandler.sendEmptyMessage(MSG_PAY_AUDIOS);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(900);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            animationHandler.sendEmptyMessage(MSG_PAY_AUDIOS);
                        }
                    }).start();
                } else if (3 - index == 3) {
                    ivNum.setImageResource(R.mipmap.ico_3);
                    animationHandler.sendEmptyMessage(MSG_PAY_AUDIOS);
                }

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                animationHandler.sendEmptyMessageDelayed(MSG_OUT_ANIMATION, audios.get(index).get("duration"));
            }
        };

        outAdapter = new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                ++index;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (index == audios.size()) {
                    toSportsStatus();
                    return;
                }
                animationHandler.sendEmptyMessage(MSG_IN_ANIMATION);
            }
        };
    }

    /**
     * 执行
     */
    private void execute() {
        animationHandler.sendEmptyMessage(MSG_IN_ANIMATION);
    }

    /**
     * 播放声音
     */
    private void payAudios() {
        startSoundPool.play(audios.get(index).get("id"),
                SOUNDPOOL_LEFT_VOLUME,
                SOUNDPOOL_RIGHT_VOLUME,
                SOUNDPOOL_PRIORITY,
                SOUNDPOOL_LOOP,
                SOUNDPOOL_RATE);
    }

    /**
     * 进场动画
     */
    private void inAnimator() {
        final ImageView iv = ivNum;
        AnimatorSet animatorSet = new AnimatorSet();
        ValueAnimator alpha = ValueAnimator.ofInt(0, 255);
        alpha.setDuration(ANIMATION_DURATION);
        alpha.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int vulue = (int) animation.getAnimatedValue();
                if (iv != null) {
                    iv.setImageAlpha(vulue);
                }
            }
        });

        ValueAnimator scale = ValueAnimator.ofInt(0, 179);
        scale.setDuration(ANIMATION_DURATION);
        scale.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int vulue = (int) animation.getAnimatedValue();
                if (iv != null) {
                    iv.getLayoutParams().height = DensityUtil.dip2px(SportsStatusActivity.this, vulue);
                    iv.requestLayout();
                }
            }
        });

        animatorSet.play(alpha);
        animatorSet.play(scale);
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        animatorSet.addListener(inAdapter);
        animatorSet.start();
    }

    /**
     * 出场动画
     */
    private void outAnimator() {
        final ImageView iv = ivNum;
        AnimatorSet animatorSet = new AnimatorSet();
        ValueAnimator alpha = ValueAnimator.ofInt(255, 0);
        alpha.setDuration(ANIMATION_DURATION);
        alpha.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int vulue = (int) animation.getAnimatedValue();
                if (iv != null) {
                    iv.setImageAlpha(vulue);
                }
            }

        });

        ValueAnimator scale = ValueAnimator.ofInt(179, 249);
        scale.setDuration(ANIMATION_DURATION);
        scale.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int vulue = (int) animation.getAnimatedValue();
                if (iv != null) {
                    iv.getLayoutParams().height = DensityUtil.dip2px(SportsStatusActivity.this, vulue);
                    iv.requestLayout();
                }
            }
        });

        animatorSet.play(alpha);
        animatorSet.play(scale);
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        animatorSet.addListener(outAdapter);
        animatorSet.start();
    }

    /**
     * 清除动画
     */
    private void clearAnimation() {
        ivNum.clearAnimation();
    }

    /**
     * 10进制转化16进制
     *
     * @param value
     * @return
     */
    private String getHexString(int value) {
        String hexString = Integer.toHexString(value);
        if (hexString.length() == 1) {
            hexString = "0" + hexString;
        }
        return hexString;
    }

    /**
     * 获取声音时长
     *
     * @param res
     * @return
     */
    private int getAudioDuration(int res) {
        MediaPlayer mediaPlayer = MediaPlayer.create(this, res);
        return mediaPlayer.getDuration();
    }

    /**
     * 进入运动状态界面
     */
    private void toSportsStatus() {
        Iterator<Map.Entry<Integer, Map<String, Integer>>> entries = audios.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<Integer, Map<String, Integer>> entry = entries.next();
            startSoundPool.stop(entry.getValue().get("id"));
        }
        startSoundPool.release();

        startSports();
    }

    private void startSports() {
        JSONObject object = new JSONObject();
        try {
            object.put("type", sportsType);
            object.put("weather", weatherType);
            object.put("phoneModel", BackStageManagementUtil.getMobileType());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ChallengeAPI().onStartChallenge(object.toString(), new BaseResultCallback<StartChallengeEntity>() {
            @Override
            public void onResponse(StartChallengeEntity response) {
                clearAnimation();
                animationHandler.removeCallbacksAndMessages(null);
                rl_start_animation.setVisibility(View.GONE);
                ll_content.setVisibility(View.VISIBLE);
                initSportsView();
            }

            @Override
            public void onError(Throwable e, String body) {
                super.onError(e, body);
                clearAnimation();
                animationHandler.removeCallbacksAndMessages(null);
                rl_start_animation.setVisibility(View.GONE);
                ll_content.setVisibility(View.VISIBLE);
                initSportsView();
            }
        });
    }

    private static class AnimationHandler extends Handler {
        private WeakReference<SportsStatusActivity> reference;

        private AnimationHandler(SportsStatusActivity activity) {
            this.reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            SportsStatusActivity activity = reference.get();
            if (activity == null) {
                return;
            }
            switch (msg.what) {
                case MSG_IN_ANIMATION:
                    activity.inAnimator();
                    break;
                case MSG_OUT_ANIMATION:
                    activity.outAnimator();
                    break;
                case MSG_PAY_AUDIOS:
                    activity.payAudios();
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    }
}
